<!-- 带描边效果的ICON -->
<template>
  <icon :id="id" :class="className" :color="color" :icon-name="name"></icon>
</template>
<!--自定义图标展示组件，通过图标名称展示图标-->
<script lang="ts">
import Icon from "@/components/Icon.vue";

export default {
  components: {Icon},
  props: {
    // icon名称
    name: {type: String},
    //描边颜色
    color: {type: String},
    // 动画持续时间
    duration: {type: Number}
  },
  data() {
    return {
      timer: {},
      className: "icon-animation",
      id: new Date().getTime() + this.$props.name+"_"+Math.random()
    }
  },
  mounted() {
    //动画持续时间，默认2秒
    const duration = this.$props.duration ? this.$props.duration : 2000;
    //设置定时器，关闭描边
    this.timer = setTimeout(() => {
      this.className = null;
    }, duration );

    const root = document.getElementById(this.id);
    let color = root.attributes.getNamedItem("color");
    const paths = root.querySelectorAll("path");
    paths.forEach((path) => {
      const len = path.getTotalLength() + 1 + "";
      path.style.setProperty("--length", len);
      //设置描边颜色
      path.style.setProperty("--color", color ? color.value : "black");
      //设置描边动画时长
      path.style.setProperty("--duration", duration * 2 + "ms");
      //设置class，根据class选择描边元素
      path.classList.add("stroke");
    });
  },
  beforeUnmount() {
    clearTimeout(this.timer);
  },
}
</script>
<style scoped>
.icon-animation :deep(.stroke) {
  stroke: var(--color);
  stroke-width: 10;
  stroke-dasharray: var(--length);
  stroke-dashoffset: var(--length);
  animation: stroke var(--duration) forwards;
  fill: none;
}

@keyframes stroke {
  to {
    stroke-dashoffset: 0;
  }
}
</style>
